﻿using System.Collections.Generic;
using Didaku.QEngine.Common.Wrapper;

namespace Didaku.QEngine.Common.Entities.Collections
{
    public class WorkflowNodeCollection : LinkedList<WorkflowNode>
    {
        public WorkflowNode this[int i]
        {
            get
            {
                if (i > Count || i < 0)
                    return null;
                var n = First;
                for (var j = 0; j < Count; j++)
                {
                    if (n == null)
                        return null;
                    if (j == i)
                        return n.Value;
                    n = n.Next;
                }
                return null;
            }
            set
            {
                var n = First;
                for (var j = 0; j < Count; j++)
                {
                    if (j == i)
                    {
                        if (n != null) 
                            AddAfter(n, value);
                        else
                            AddFirst(value);
                        var old = Find(value);
                        if (old != null && old.Next != null)
                            Remove(old.Next);
                    }
                    if (n != null) 
                        n = n.Next;
                }
            }
        }

        public void Add(WorkflowNode node)
        {
            AddLast(node);
        }

        public WorkflowNode NextNode(short order)
        {
            LinkedListNode<WorkflowNode> node = First;
            while (node != null)
            {
                if (node.Value.Order == order)
                {
                    if (node.Next != null) 
                        return node.Next.Value;
                    return null;
                }
                node = node.Next;
            }
            return null;
        }
    }
}